package com.sam.expensetracker;

import java.util.Date;
import java.util.Vector;

import net.rim.blackberry.api.homescreen.HomeScreen;
import net.rim.device.api.system.Characters;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.component.BasicEditField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;
import net.rim.device.api.ui.component.ObjectChoiceField;
import net.rim.device.api.ui.component.TextField;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.text.TextFilter;
import net.rim.device.api.util.NumberUtilities;

import com.sam.expensetracker.dao.ExpRec;

/**
 * A class extending the MainScreen class, which provides default standard
 * behavior for BlackBerry GUI applications.
 */
public final class MyScreen extends MainScreen {
	/**
	 * Creates a new MyScreen object
	 */
	Vector vector;
	MenuItem newExpItem, editExpItem, deleteExpItem;
	ListField listField;
	LabelField debtField;

	public MyScreen() {
		// Set the displayed title of the screen
		setTitle("Expense tracker");
		vector = new Vector();
		vector = MyApp.dbObject.vector;
		newExpItem = new MenuItem("New", 0, 0) {
			public void run() {
				String choices[] = { "Ok", "Cancel" };
				Dialog dialog = new Dialog("New Expense", choices, new int[] {
						0, 1 }, 0, null);
				EditField descEditField = new EditField("desc: ", ""), aaEditField = new EditField(
						"type1: ", "0"), asEditField = new EditField("type2: ",
						"0"), saEditField = new EditField("type3: ", "0"), ssEditField = new EditField(
						"type4: ", "0");
				aaEditField.setFilter(TextFilter.get(TextFilter.NUMERIC));
				asEditField.setFilter(TextFilter.get(TextFilter.NUMERIC));
				saEditField.setFilter(TextFilter.get(TextFilter.NUMERIC));
				ssEditField.setFilter(TextFilter.get(TextFilter.NUMERIC));

				net.rim.device.api.ui.component.DateField dateField = new net.rim.device.api.ui.component.DateField(
						"Time : ", System.currentTimeMillis(),
						net.rim.device.api.ui.component.DateField.DATE_TIME);
				String categoryChoices[] = { "Food", "Travel", "Misc",
						"Restaurant", "Monthly Exp.", "Other" };
				ObjectChoiceField categoryField = new ObjectChoiceField(
						"Category :", categoryChoices);
				dialog.add(dateField);
				dialog.add(categoryField);
				dialog.add(descEditField);
				dialog.add(aaEditField);
				dialog.add(asEditField);
				dialog.add(saEditField);
				dialog.add(ssEditField);
				descEditField.setFocus();
				if (dialog.doModal() == 0) {
					vector.addElement(new ExpRec(new Date(dateField.getDate()),
							categoryChoices[categoryField.getSelectedIndex()],
							descEditField.getText(), Integer
									.parseInt(aaEditField.getText()), Integer
									.parseInt(asEditField.getText()), Integer
									.parseInt(saEditField.getText()), Integer
									.parseInt(ssEditField.getText())));
					refreshScreen();
				}
			};
		};
		deleteExpItem = new MenuItem("Delete", 0, 0) {
			public void run() {
				if (vector.size() > 0) {
					vector.removeElementAt(listField.getSelectedIndex());
					refreshScreen();
				}
			};
		};
		listField = new ListField();
		listField.setRowHeight(56);
		listField.setCallback(new ExpenseListFieldCallback());
		debtField = new LabelField(debtField, LabelField.FIELD_RIGHT) {
			protected void paint(Graphics graphics) {
				graphics.setColor(Color.BURLYWOOD);
				super.paint(graphics);
			};
		};
		debtField.setMargin(5, 0, 5, 0);
		add(debtField);
		add(listField);
		addMenuItem(newExpItem);
		addMenuItem(deleteExpItem);
		refreshScreen();
	}

	protected boolean keyChar(char c, int status, int time) {
		// TODO Auto-generated method stub
		if (c == 'n')
			newExpItem.run();
		else if (c == 'd' || c == Characters.BACKSPACE)
			deleteExpItem.run();

		return super.keyChar(c, status, time);
	}

	public boolean onClose() {
		MyApp.dbObject.vector = vector;
		HomeScreen.setName(getAppIconName());
		return super.onClose();
	}

	public String getAppIconName() {
		int total = ExpRec.getDebt(vector);
		int totalMod = Math.abs(total);
		String str = "";
		if (totalMod < 499)
			return "Expenses";
		else if (totalMod <= 999)
			str = "" + total;
		else {
			double d = total / 1000.0;

			str = "" + d + "K";
		}
		return "Expns(" + str + ")";
	}

	public void refreshScreen() {
		listField.setSize(vector.size());
		debtField.setText("Debt : " + ExpRec.getDebt(vector));

	}

	class ExpenseListFieldCallback implements ListFieldCallback {

		public void drawListRow(ListField listField, Graphics graphics,
				int index, int y, int width) {
			ExpRec expRec = ((ExpRec) vector.elementAt(index));

			int amountTextWidth = getFont()
					.getAdvance(expRec.getNetDebt() + "") + 5;
			graphics.setColor(Color.NAVY);
			graphics.drawText("" + expRec.getNetDebt(), Display.getWidth()
					- amountTextWidth, y + 8, 0, amountTextWidth);
			graphics.setColor(Color.BLACK);
			graphics.drawText(expRec.category + " : ", 5, y + 8, 0,
					Display.getWidth() - amountTextWidth - 10);
			Font font = Font.getDefault().derive(Font.BOLD, 14);
			graphics.setFont(font);
			int dateFieldWidth = font.getAdvance(expRec.day) + 5;
			graphics.setColor(Color.GRAY);
			graphics.drawText(expRec.day, Display.getWidth() - dateFieldWidth,
					y + 26, 0, dateFieldWidth);
			font = Font.getDefault().derive(Font.ITALIC, 16);
			graphics.setFont(font);
			graphics.setColor(Color.BLACK);
			graphics.drawText(expRec.desc, 5, y + 26, 0, Display.getWidth()
					- dateFieldWidth - 8);

		}

		public Object get(ListField listField, int index) {
			// TODO Auto-generated method stub
			return vector.elementAt(index);
		}

		public int getPreferredWidth(ListField listField) {
			// TODO Auto-generated method stub
			return Display.getWidth();
		}

		public int indexOfList(ListField listField, String prefix, int start) {
			// TODO Auto-generated method stub
			return vector.indexOf(prefix, start);
		}
	}
}
